import os
import exifread
import datetime
import hashlib
import json
import shutil


def getallfiles(path):
    allfile = []
    for dirpath, dirnames, filenames in os.walk(path):
        for name in filenames:
            if name.endswith(".jpg"):   # or name.endswith(".mkv"):
                allfile.append(os.path.join(dirpath, name))
    return allfile

def load_from_file(file_dir):
    # file = "D:\\photo\\2022\\IMG_20210625_145140.jpg"
    is_failed = False
    root_dir = "Z:\\photo2"
    base_dir, file_name = os.path.split(file_dir)
    dest_dir, dest_file, dt = "", "", None
    try:
        file = open(file_dir, mode='rb')
        tags = exifread.process_file(file)
        if "Image Model" in tags:
            model = str(tags["Image Model"])
            model = model.strip().replace(" ", "").replace("/", "")
        else:
            model = "unknown"
        if "Image DateTime" in tags:
            imageDateTime = str(tags["Image DateTime"])
        elif "EXIF DateTimeOriginal" in tags:
            imageDateTime = str(tags["EXIF DateTimeOriginal"])
        else:
            if "mmexport" in file_name or "wx_camera" in file_name or "microMsg.microMsg_" in file_name or file_name.startswith(
                    "1558") or file_name.startswith("1658"):
                photo_timestamp = int(
                    file_name.replace("mmexport", "").replace("wx_camera_", "").replace("microMsg.microMsg_",
                                                                                        "").replace(".jpg", "").replace(
                        ".jpeg", "")) / 1000
                dt = datetime.datetime.fromtimestamp(photo_timestamp)
            else:
                print("err")
                is_failed = True
                return
            # 'EXIF DateTimeOriginal' (2411750652144)
        if dt is None:
            dt = datetime.datetime.strptime(imageDateTime, '%Y:%m:%d %H:%M:%S')
        dt_str = dt.strftime('%Y%m%d_%H%M%S')
        dest_dir = os.path.join(root_dir, "%d年" % dt.year, "%d月" % dt.month)
        dest_file = model + "_" + dt_str + ".jpg"
        # content_b = file.read()
        file.close()
        # 'Image Model' (1970665278640) printable  ONEPLUS A6010
        # 'Image DateTime' (1970665279152) printable 2021:06:25 14:51:40
    except Exception as e:
        print(e)
    finally:
        if len(dest_dir) == 0:
            return
        if not is_failed and (dest_dir != base_dir or dest_file != file_name):
            if not os.path.exists(dest_dir):
                print("dest_dir %s" % dest_dir)
                os.makedirs(dest_dir)
            dest_full = os.path.join(dest_dir, dest_file)
            if not os.path.exists(dest_full):
                print(dest_full)
                shutil.move(file_dir, dest_full)


if __name__ == '__main__':
    path = "Z:\\photo\\0"
    allfile = getallfiles(path)
    for file in allfile:
        # print(file)
        load_from_file(file)
        # break
